<?php

namespace App\Http\Controllers\Back;

use App\Http\Controllers\Controller;
use App\Model\Operators;
use App\Model\Partner;
use App\Model\Salesmen;
use App\Model\SmsMsg;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Swagger\Annotations as SWG;

/**
 * Class AuthController
 * @package App\Http\Controllers\Back
 */
class AuthController extends Controller
{
    /**
     *
     * @SWG\Post(
     *     path="/back/login",
     *     summary="密码登录",
     *     tags={"后台"},
     *     description="密码登录",
     *     consumes={"application/x-www-form-urlencoded"},
     *     produces={"application/json"},
     *     @SWG\Parameter(name="phone", in="formData", required=true, type="string", description="手机号"),
     *     @SWG\Parameter(name="password", in="formData", required=true, type="string", description="密码"),
     *     @SWG\Response(
     *         response=200,
     *         description="返回授权凭证",
     *         @SWG\Schema(
     *             type="json",
     *             @SWG\Property(property="token", type="string", description="凭证"),
     *              @SWG\Property(
     *                  property="user",
     *                  @SWG\Property(property="id", type="integer", description="用户id"),
     *                  @SWG\Property(property="u_id", type="integer", description="自己的id"),
     *                  @SWG\Property(property="p_id", type="integer", description="上级id"),
     *                  @SWG\Property(property="name", type="string", description="名字"),
     *                  @SWG\Property(property="type", type="integer", description="1管理中心2运营商3业务员"),
     *                  @SWG\Property(property="invitation_code", type="string", description="邀请码"),
     *                  @SWG\Property(property="province", type="integer", description="省份"),
     *              ),
     *         )
     *     )
     * )
     */
    public function login(Request $request)
    {
        $rules = [
            'account' => 'required|min:2|max:20|exists:users',
            'phone' => 'required_without_all:account,email',
            'email' => 'required_without_all:phone,account',
            'password' => 'required|string|min:6|max:20'
        ];
        if ($request->has('account')){
            $rules['account'] = 'required_without_all:phone,email';
            $credentials['account'] = $request->input('account');
        }

        if ($request->has('phone')){
            $rules['phone'] = ['required','regex:/^1[34578][0-9]{9}$/','exists:users'];
            $credentials['phone'] = $request->input('phone');
        }
        if ($request->has('email')){
            $rules['email'] = 'required|email|exists:users';
            $credentials['email'] = $request->input('email');
        }
        $message = [
            'required' => ':attribute不能为空',
            'exists' => ':attribute不存在',
            'min' => ':attribute不小于:min位',
            'max' => ':attribute不大于:max位',
            'phone.regex' => '手机号不正确',
            'email' => '邮箱不正确'
        ];

        $attribute = [
            'account' => '用户名',
            'phone' => '手机号',
            'email' => '邮箱',
            'password' => '密码'
        ];

        $this->validate($request, $rules, $message, $attribute);//验证

        //登录验证字段
        $credentials['password'] = $request->input('password');

        $guard = Auth::guard('admin');
        if (!$token = $guard->attempt($credentials)){
            return $this->fail('账号或密码错误');
        }
//        if ($guard->user()->type == 0){
//            return $this->fail('禁止访问', 403);
//        }
        if ($guard->user()->type >= 4){
            return $this->fail('禁止访问', 403);
        }
        if ($guard->user()->is_enabled == 1){
            return $this->fail('你的账号已被停用,请联系管理员', 403);
        }
        //登录成功记录数据
        $user = $guard->user();
//        $user->update(['logged_ip'=>$request->getClientIp(),'logged_at'=>date('Y-m-d H:i:s', time())]);
        $this->loginLog($user);
        $p = 0;
        $p_id = 0;
        $province = 0;
        if ($user->type == 1) {
            $p = Partner::where('user_id', $user->id)->first();
            $province = $p->province;
        }elseif ($user->type == 2) {
            $p = Operators::where('user_id', $user->id)->first();
            $p_id = $p->place_partner_id;
            $province = $p->province_id;
        }elseif ($user->type == 3) {
            $p = Salesmen::where('user_id', $user->id)->first();
            $p_id = $p->operator_id;
            $province= $p->province_id;
        }

        return $this->send(['token' => $token, 'user'=>['id' => $user->id, 'u_id' => $p->id, 'p_id' => $p_id, 'name'=> $user->account,'type'=>$user->type, 'invitation_code' => $user->invitation_code, 'province'=>$province]], 200);
    }

    public function reset(Request $request, User $user)
    {
        $this->validate($request, [
            'phone_number' => [
                'regex:/^(\+?0?86\-?)?((13\d|14[57]|15[^4,\D]|17[3678]|18\d)\d{8}|170[059]\d{7})$/'
            ],
            'new_password' => 'required',
            'code' => 'size:6'
        ], [
            'phone_number.regex' => '手机号格式不正确',
            'code.size' => '验证码错误',
            'new_password' => '密码是必填的'
        ]);

        $msg = new SmsMsg();
        $msg->validate($request->input('phone_number'), $request->input('code'));
        $user = $user->where(['account' => $request->input('phone_number')])->first();
        $user->password = bcrypt($request->input('new_password'));
        return $this->success();
    }

    private function loginLog(User $user)
    {
        $user->logged_ip = request()->getClientIp();
        $user->logged_at = date('Y-m-d H:i:s', time());
        $user->save();
    }


    /**
     * 获取邀请码
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function getInvitationCode(Request $request)
    {
        $id =  $request->input("id");
        $code = rand(100000,999999);
        $users =  User::where("id", $id)->first();
        $users->invitation_code = $users->id.$code;
        $users->save();
        return $this->renderJson (["code" => $users->invitation_code]);
    }
}
